<template>
  <div class="code-rain-container">
    <canvas ref="canvas"></canvas>
  </div>
</template>

<script>
export default {
  props: {
    color: {
      type: String,
      default: '#7ebf50'
    }
  },
  data() {
    return {
      canvas: null,
      ctx: null,
      str: [],
      Arr: [],
      timer: null
    }
  },
  methods: {
    render() {
      this.ctx.fillStyle = 'rgba(0, 0, 0, 0.05)'
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height)

      this.ctx.fillStyle = this.color
      this.Arr.forEach((item, index) => {
        // 初始移动距离 item + 10
        this.ctx.fillText(this.str[Math.floor(Math.random() * this.str.length)], index * 10, item + 10)
        // Arr[index] = item > canvas.height ? 0 : item + 10
        // 超过画布大小置为0位置，否则移动距离+10
        // 随机数控制数组各个元素的垂直偏移量不会完全一致，形成错落感
        this.Arr[index] = item > this.canvas.height || item > 5000 * Math.random() ? 0 : item + 15
      })
      if (this.timer) clearTimeout(this.timer)
      this.timer = setTimeout(() => requestAnimationFrame(this.render), 50)
    }
  },
  mounted() {
    this.canvas = this.$refs.canvas
    this.ctx = this.canvas.getContext('2d')
    const rect = this.canvas.parentNode.getBoundingClientRect()
    this.canvas.width = rect.width
    this.canvas.height = rect.height
    this.str = 'LINZEXZUTOMAYO1010HIDE404AN94UMP4590'.split('')

    this.Arr = Array(Math.ceil(this.canvas.width / 10)).fill(0)
    this.render()
  }
}
</script>

<style lang="less" scoped>
.code-rain-container, canvas {
  width: 100%;
  height: 100%;
  display: block;
}
</style>